﻿using RpcClient.Interface;
using RpcHelper;
using RpcHelper.Config;
using RpcModel;
using RpcSync.Collect;
using RpcSync.Collect.Model;

namespace RpcSync.Service.ConfigService
{
    /// <summary>
    /// 用于替换本地配置服务数据来源
    /// </summary>
    internal class ConfigServer : IConfigServer
    {
        private ISysConfigCollect _SysConfig => RpcClient.RpcClient.Unity.Resolve<ISysConfigCollect>();
        private MsgSource Source => RpcClient.RpcClient.CurrentSource;

        public string GetConfigVal(string name)
        {
            if (!RpcClient.RpcClient.IsInit)
            {
                return null;
            }
            SysConfigItem item = _SysConfig.GetSysConfig(this.Source.SystemType);
            return item.GetConfigVal(name, this.Source);
        }

        public T GetConfigVal<T>(string name)
        {
            string str = GetConfigVal(name);
            if (string.IsNullOrEmpty(str))
            {
                return default;
            }
            return str.Parse<T>();
        }

        public T GetConfigVal<T>(string name, T defValue)
        {
            string str = GetConfigVal(name);
            if (string.IsNullOrEmpty(str))
            {
                return defValue;
            }
            return str.Parse<T>();
        }

        public void LoadConfig()
        {
            SysConfigItem item = _SysConfig.GetSysConfig(this.Source.SystemType);
            item.Items.ForEach(a =>
           {
               if (a.ValueType == RpcSync.Model.SysConfigValueType.JSON)
               {
                   LocalConfig.Local.SetJson(a.Name, a.Value, a.Prower);
               }
               else
               {
                   LocalConfig.Local.SetConfig(a.Name, a.Value, a.Prower);
               }
           });
        }
    }
}
